(function($){  
      
    $.fn.gallery = function(options){  
      
        
        return this.each(function() {
            var element = $(this);
            var opts = $.extend({}, $.fn.gallery.defaults, options);
            $('<div class="gallery-pager"></div>').appendTo("#"+element.attr("id"));
            getPhotos(opts.photoSet, 1, opts.photosPerPage, element.attr("id"));
   
            $("#"+element.attr('id')+" .gallery-pager .page-navigation :button").live('click', function(event) {
                if(!$(this).hasClass('none') && !$(this).hasClass('med') && $(this).attr('disabled') === undefined){
                    $("#"+element.attr('id')+" .gallery-pager  .page-navigation :button").attr("disabled", "disabled");
                    getPhotos(opts.photoSet,$(this).attr("id"),opts.photosPerPage,element.attr("id"));
                }
            });  
        });              

    };
    

    
    function getPhotos(photoSet, pageNumber, photosPerPage, elementId){
        $('#'+elementId+' .gallery-container' ).remove();
        $('<div class="gallery-container"></div>').prependTo("#"+elementId);
        
        if(photoSet == null){
            $('<p>Debes elegir un photoset</p>').appendTo('#'+elementId);
            return;
        }

        $('<img />').attr('class', 'loader').attr('src', 'http://jquery-flickr-gallery.googlecode.com/svn/trunk/images/loading_bar.gif').prependTo('#'+elementId);


        var apiKey = 'd8ed58348bb7d25a8aaf8676ede4afb2';

        $.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key=' + apiKey + '&photoset_id='+photoSet+'&extras=url_t%2C+url_m&privacy_filter=5&per_page='+photosPerPage+'&page='+pageNumber+'&format=json&jsoncallback=?',
            function(data, status){

                if(data.stat == "ok"){
                    var pages = data.photoset.pages;
                    var curr_page = data.photoset.page;
                    var prev = data.photoset.page - 1;
                    var next = parseInt(data.photoset.page) + 1;
                    $('.gallery-container').append('<table id="image-grid">');
                    var count=1;
                    var add = 3;
                    $.each(data.photoset.photo, function(i,item){                          
                        var img = new Image();
                        //alert(i);
                        if(i <= 0){
                            $('#image-grid').append('<tr id="'+count+'">');
                        }else if(i > add){
                            count++;
                            add += 4;
                            $('#image-grid').append('<tr id="'+count+'">');
                        }
                        
                        $(img).hide();
                        $('#image-grid tbody #'+count).append(img);
                        //alert(item.height_t);
                        $(img).wrap('<div class="load loading '+item.id+'" style="height:'+item.height_t+';width:'+item.width_t+';"/>');
                        $(img).wrap('<a  rel="lightbox-'+elementId+'" href="'+item.url_m+'" title="'+item.title+'" class="main-img" />');
                        $('.'+item.id).wrap('<td>');
                        $(img).fadeIn();
                        $(img).attr('src', item.url_t);
                        $.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id='+item.id+'&format=json&jsoncallback=?',
                            function(photo, status){
                                //var content = photo.photo.description._content.replace(",","<br/>");
                                var content = photo.photo.description._content;
                                $('#'+elementId+' .gallery-container .'+item.id).append('<div class="mas-info" style="display:none;"title="'+content+'"><a href="http://jquery-flickr-gallery.googlecode.com/svn/trunk/photoinfo.html?id='+item.id+'" class="info">Mas Info.<img src="http://jquery-flickr-gallery.googlecode.com/svn/trunk/images/001_03.png"/></a></div>');
                                $('#'+elementId+' .gallery-container .'+item.id+' .mas-info').fadeIn();
                                //                                $("a[rel^='lightbox']").slimbox({/* Put custom options here */}, function(el) {
                                //                                    return [el.href, el.title + '<br /><a href="' + el.href + '">Download this image</a>'];
                                //                                }, function(el) {
                                //                                    return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
                                //                                });
                                $(".gallery-container .main-img").fancybox();
                                
                                
                                $("a.info").fancybox({
                                    'width': '100%',  //or whatever
                                    'height': '100%',
                                    'type': 'iframe',
                                    'transitionIn': 'elastic',
                                    'centerOnScroll': true
                                });
                                

                                $(img).load(function(){
                                    $(img).fadeIn();
                                    $('.load').removeClass('loading');                                 
                                });
                           
                                
                            }); 
                            
                    });
             
                 
                                      
                    if(pages > 1){                                   
                        var pager = '<p class="page-navigation">';
           
                        if (curr_page <= 1){
                            pager = pager + '<input type="button" class="previous bold none" value="Anterior"/>';
                        }else{
                            i = parseInt(curr_page) - 1;
                            pager = pager + '<input type="button" id="'+prev+'" class="previous bold" value="Anterior"/>';
                        }
                  
                        for(var j = 1; j <= pages; j++){
               
                            if (curr_page == j){
               
                                pager = pager + ' | <input type="button" id="'+j+'" class="med" value="'+j+'"/>';
                            }else{
                                pager = pager + ' | <input type="button" id="'+j+'" value="'+j+'"/>';
                            }
                        }
                    
                        if (curr_page >= pages){
                            pager = pager + ' | <input type="button" class="next bold none" value="Siguiente"/>';
                        }else{
                            i = parseInt(curr_page)  + 1;
                            pager = pager + ' | <input type="button" id="'+next+'" class="next bold" value="Siguiente"/>';
                        }
            
            
            
            
                        $('#'+elementId+' .gallery-pager').html(pager);
                    }                                                        
                }else{
                    $('#'+elementId+' .gallery-container').html('<h2>'+data.stat+': '+data.message+'</h2>');
                    
                }
            });


        $(".loader").fadeOut("slow",function(){
            $('.loader').delay(3000).remove(); 
        });
    

    };

    
    $.fn.gallery.defaults = {
        photosPerPage: 15,
        photoSet: null
    };
    
    
        
        
        
   
})(jQuery);  